package globals;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class StopWatch {

	private static StopWatch sw = null;
	
	private long startTime; 
	private long stopTime; 
	private long elapsedTime;
	private boolean running; 
	private boolean outputLog;
	private int  stopCounter;
	
	public StopWatch(){
		this.reset();
		this.outputLog = false;
		this.stopCounter = 0;
	}
	
	public void reset(){
		this.elapsedTime = 0;
		this.running = false;
		this.startTime = 0;
		this.stopTime = 0;
	}
	
	public void start(){
		if(this.running){
			System.err.println("StopWatch already running."); 
			return;
		} else {
			this.running = true;
			this.stopTime = 0;
			this.startTime = System.currentTimeMillis();
			return;
		}
	}
	
	public long stop(){
		if(!this.running){
			System.err.println("StopWatch not running."); 
			return 0;
		} else {
			this.stopTime = System.currentTimeMillis();
			this.elapsedTime += this.stopTime - this.startTime;
			this.running = false;
			if(this.outputLog){
				String logstr = ""+(++this.stopCounter)+","+
						(this.stopTime - this.startTime)+","+this.elapsedTime;
				this.writeToLog(logstr);
			}
			return this.stopTime - this.startTime;
		}
	}
	
	public long totalElapsedTime(){
		if(this.running){
			return (this.elapsedTime + System.currentTimeMillis() - this.startTime);
		} else {
			return this.elapsedTime;
		}
	}
	
	public static StopWatch getGlobalStopWatch(){
		if(StopWatch.sw == null){
			StopWatch.sw = new StopWatch();
		}
		return StopWatch.sw;
	}
	
	public void useLog(boolean use){
		this.outputLog = use;
		if(this.outputLog){
			DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
	        Date date = new Date();
			this.writeToLog("Started measurement: "+dateFormat.format(date));
		}
	}
	
	public void addTime(long time){
		this.elapsedTime += time;
	}
	
	private void writeToLog(String s){
		DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
		String filename = "SW"+dateFormat.format(date)+".txt";
		try {
			BufferedWriter bw = new BufferedWriter(new FileWriter(filename,true));
			bw.write(s+"\n");
			bw.flush();
			bw.close();
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(-2);
		}
	}
	
}
